#!/usr/bin/env node

let axios = require('axios')
let inquirer = require('inquirer')
let chalk = require('chalk')

let time = 1000

main(time)

function main(time) {
    // 获取赛事列表 url
    let getListUrl = 'https://bifen4m.qiumibao.com/json/list.htm'

    axios(getListUrl).then(res => {
        let items = []
        let data = res.data
        let pattern = /[a-z]{1,}\.live/

        for (let list of data.list) {
            if (list.period_cn !== '完赛' && list.period_cn && pattern.test(list.from)) {
                items.push(list)
            }
        }
        if (items.length === 0) {
            console.log('当前没有可观看的赛事')
            return 0
        } else {
            inquirer.prompt([{
                    type: 'list',
                    name: 'matchId',
                    message: '请选择想观看的赛事：',
                    pageSize: 12,
                    choices: items2choices(items)
                }])
                .then(answer => {
                    matchId = answer.matchId
                    let TextId = -1

                    console.log('正在获取比赛信息...')
                    console.log()

                    setInterval(_ => {
                        axios(`https://dingshi4pc.qiumibao.com/livetext/data/cache/max_sid/${matchId}/0.htm`).then(res => {
                            if (TextId !== res.data) {
                                TextId = res.data
                                axios(`https://dingshi4pc.qiumibao.com/livetext/data/cache/livetext/${matchId}/0/lit_page_2/${TextId}.htm`)
                                    .then(res => {
                                        for (let list of res.data) {
                                            console.log(`当前时间：${chalk.blue(list.pid_text)}  当前比分：${chalk.green(list.home_score)}:${chalk.green(list.visit_score)}`)
                                            console.log(`${list.user_chn}：${list.live_text}`)
                                            console.log()
                                        }
                                    }).catch(err => {})
                            }
                        }).catch(err => {})
                    }, time)

                })
        }
    })


}


/**
 * 把赛事 items 转换为选项 choices
 * @param {Array} items 
 * @return {Array} choices
 */
function items2choices(items) {
    let choices = []
    for (let item of items) {
        choices.push({
            name: `${item.home_team} VS ${item.visit_team}`,
            value: item.id
        })
    }
    return choices
}
